<template>
  <div class="preview-wraper">
    <div class="preview-sub" ref="preview">
      <span style="display: none;">{{ fileName }}</span>
      <el-tooltip
        v-if="overFlowWidth"
        effect="dark"
        :content="fileName"
        placement="top"
      >
        <span>{{ fileName }}</span>
      </el-tooltip>
      <span v-else>{{ fileName }}</span>
    </div>
    <slot />
  </div>
</template>
<script>
export default {
  name: 'ellipsisForText',
  props: {
    fileName: {
      type: [String],
      default: ''
    }
  },
  data() {
    return {
      overFlowWidth: false
    }
  },
  watch: {
    // 文件名称变化 宽度就会变化
    fileName() {
      setTimeout(() => {
        this.calculateWidth()
      }, 1100)
    }
  },
  mounted() {
    setTimeout(() => {
      this.calculateWidth()
    }, 1100)
  },
  methods: {
    calculateWidth() {
      if (this.$refs['preview']) {
        let offSetWidth = this.$refs['preview'].clientWidth
        let scrollWidth = this.$refs['preview'].scrollWidth
        this.overFlowWidth = scrollWidth > offSetWidth
      }
    }
  }
}
</script>

<style scoped>
.preview-wraper {
  width: 100%;
  display: flex;
  align-items: center;
}
.preview-sub {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
